package main

import (
	"fmt"
	"github.com/kardianos/service"
	"log"
	"os"
	"path/filepath"
	"runtime"
	"time"
)

var logger service.Logger

// program 结构体实现 service.Service 接口
type program struct{}

// Start 方法在服务启动时调用
func (p *program) Start(s service.Service) error {
	go p.run()
	return nil
}

// run 方法是服务的主逻辑
func (p *program) run() {
	for {

		main_server()
		time.Sleep(5 * time.Second)
	}
}

// Stop 方法在服务停止时调用
func (p *program) Stop(s service.Service) error {
	return nil
}

var execName = ""
var execNamePath = ""
var runFileServer = ""

func iniExePath() {
	if execNamePath == "" {
		// 获取执行文件的绝对路径
		execPath, err := os.Executable()
		if err != nil {
			logger.Error("Failed to install service:", err)
			return
		}
		// 提取文件名（不包含路径）
		execName = filepath.Base(execPath)
		// 提取文件名（不包含路径）
		execName = filepath.Base(execPath)
		execNamePath = filepath.Dir(execPath)

		// 根据操作系统选择命令
		switch runtime.GOOS {
		case "windows":
			runFileServer = execName[:len(execName)-4] + "_v.exe"
		case "linux":
			runFileServer = execName + "_v"
		default:

		}
	}

}

/*
编译linux可执行文件
go env -w CGO_ENABLED=0
go env -w GOOS=linux
go env -w GOARCH=amd64
go build -ldflags "-s -w" -o daemon-server
编译window可执行文件
go env -w CGO_ENABLED=1
go env -w GOOS=windows
go env -w GOARCH=amd64
go build -ldflags "-s -w" -o daemon-server.exe
*/
func main() {
	iniExePath()
	// 创建服务配置
	svcConfig := &service.Config{
		Name:        execName,                                     // 服务名称
		DisplayName: execName,                                     // 显示名称
		Description: "Go Program as a Service run ***_server.exe", // 服务描述
	}

	// 创建服务实例
	prg := &program{}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		log.Fatal("Failed to create service:", err)
	}

	// 初始化日志
	logger, err = s.Logger(nil)
	if err != nil {
		log.Fatal("Failed to create logger:", err)
	}

	// 处理命令行参数
	if len(os.Args) > 1 {
		cmd := os.Args[1]
		switch cmd {
		case "install":
			err = s.Install()
			if err != nil {
				logger.Error("Failed to install service:", err)
			} else {
				logger.Info("Service installed successfully")
			}
		case "remove":
			stopProcess()
			err = s.Uninstall()
			if err != nil {
				logger.Error("Failed to remove service:", err)
			} else {
				logger.Info("Service removed successfully")
			}
		case "start":
			err = s.Start()
			if err != nil {
				logger.Error("Failed to start service:", err)
			} else {
				logger.Info("Service started successfully")
			}
		case "run":
			err = main_server()
			if err != nil {
				logger.Error("start Server:", err)
			} else {
				logger.Info("start Server: ok")
			}
			status, err := s.Status()
			if err != nil {
				logger.Error("Failed to get service status:", err)
			} else {
				logger.Info("Service reload status:", status)
			}
		case "reload":
			err = stopProcess()
			if err != nil {
				logger.Error("stop Server:", err)
			} else {
				logger.Info("stop Server: ok")
			}
			err = main_server()
			if err != nil {
				logger.Error("start Server:", err)
			} else {
				logger.Info("start Server: ok")
			}
			status, err := s.Status()
			if err != nil {
				logger.Error("Failed to get service status:", err)
			} else {
				logger.Info("Service reload status:", status)
			}
		case "stop":
			err = stopProcess()
			if err != nil {
				logger.Error("stopProcess:", err)
			}
			err = s.Stop()
			if err != nil {
				logger.Error("Failed to stop service:", err)
			} else {
				logger.Info("Service stopped successfully")
			}
		case "status":
			status, err := s.Status()
			if err != nil {
				logger.Error("Failed to get service status:", err)
			} else {
				logger.Info("Service status:", status)
			}
		default:
			fmt.Printf("Usage: %s install | remove | start | stop | status\n", os.Args[0])
		}
		return
	}

	// 运行服务
	err = s.Run()
	if err != nil {
		logger.Error("Service failed:", err)
	}
}
